#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mpi_isp.h"
#include "mpi_sys.h"
#include "mpi_vo.h"
#include "mpi_vi.h"
#include "media/mm_comm_vi.h"
#include "media/mpi_vi.h"
#include "vo/hwdisplay.h"
#include "log/log_wrapper.h"

#include <ClockCompPortIndex.h>
#include <mpi_videoformat_conversion.h>
#include <confparser.h>
#include <utils/plat_log.h>

#include <plat_type.h>
#include <tsemaphore.h>
#include <mm_comm_vo.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 设置窗口为透明  
    setAttribute(Qt::WA_TranslucentBackground);  
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    // 设置按钮样式  
    ui->pushButton->setStyleSheet("background-color: rgba(255, 255, 255, 255);");  
}

MainWindow::~MainWindow()
{
    on_pushButton_close_clicked();
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    // const QString configFilePath = "sample_virvi2vo.conf";

    // WorkerThread *worker = new WorkerThread(configFilePath); // 创建工作线程
    // connect(worker, &WorkerThread::resultReady, this, [this](int result) {
    //     if (result == 0) {
    //         printf("SampleVIRVI2VO executed successfully.\n");
    //     } else {
    //         printf("SampleVIRVI2VO execution failed with error code: %d\n", result);
    //     }
    // });
    // worker->start(); // 启动线程

    if (!worker) { // Create a new worker thread only if it does not exist  
        worker = new WorkerThread(configFilePath); // Create the worker thread  
        connect(worker, &WorkerThread::resultReady, this, [this](int result) {
            if (result == 0) {  
                printf("SampleVIRVI2VO executed successfully.\n");  
            } else {  
                printf("SampleVIRVI2VO execution failed with error code: %d\n", result);  
            }  
        });  
        worker->start(); // Start the thread  
    }  
}

void MainWindow::on_pushButton_close_clicked()
{
    handle_exit(0);
    if (worker) { // Check if the worker thread exists  
        worker->quit(); // Request the thread to quit  
        worker->wait(); // Wait for the thread to finish  
        delete worker; // Clean up the worker instance  
        worker = nullptr; // Set worker to nullptr to avoid dangling pointer  
    }  
}
